import 'dart:collection';

import 'package:dio/dio.dart';
import 'package:wuxu_flutter_lianxi/net/interceptors/HeaderInterceptor.dart';
import 'package:wuxu_flutter_lianxi/net/result_data.dart';

import 'code.dart';
import 'interceptors/LogsInterceptor.dart';
import 'interceptors/TokenInterceptor.dart';

///
/// 网络请求核心类
///
/// 本项目使用dio作为核心网络框架
///
class HttpManager {
  final Dio _dio = Dio();

  HttpManager() {
    //设定拦截器
    _dio.interceptors.add(HeaderInterceptor());
    _dio.interceptors.add(LogsInterceptor());
    _dio.interceptors.add(TokenInterceptor());
  }

  Future<ResultData> netFetch(url, params,
      {Map<String, dynamic>? header, Options? option, noTip = false}) async {
    //创建headers
    Map<String, dynamic> headers = HashMap();
    if (header != null) {
      headers.addAll(header);
    }

    if (option != null) {
      option.headers = headers;
    } else {
      option = Options(method: "get");
      option.headers = headers;
    }

    resultError(DioException e) {
      Response? errorResponse;
      if (e.response != null) {
        errorResponse = e.response;
      } else {
        errorResponse = Response(
            statusCode: 666, requestOptions: RequestOptions(path: url));
      }
      if (e.type == DioExceptionType.connectionTimeout ||
          e.type == DioExceptionType.sendTimeout ||
          e.type == DioExceptionType.receiveTimeout) {
        errorResponse!.statusCode = Code.NETWORK_TIMEOUT;
      }
    var result =   ResultData(
          Code.errorHandleFunction(
              errorResponse!.statusCode, e.message ?? "", noTip),
          false,
          errorResponse.statusCode);

      return result;
    }

    Response response;
    //dio 核心方法
    try {
      response = await _dio.request(url, data: params, options: option);
    } on DioException catch (e) {
      return resultError(e);
    }

    if (response.data is DioException) {
      return resultError(response.data);
    }

    return ResultData(response.data, true, response.statusCode);
  }
}

final HttpManager httpManager = HttpManager();
